import { MenuOutlined } from '@ant-design/icons';
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import React, { useEffect } from 'react';
import { YmForm } from 'ym-design';
import EditTableRowContext from './context/EditTableRowContext';
import type { EditTableRowProps } from './interface';

const EditTableRow: React.FC<EditTableRowProps> = (props) => {
  const {
    index,
    record,
    rowKey,
    fieldNames,
    addFormInstance,
    removeFormInstance,
    onRowValuesChange,
    formInitialValues,
    dragAndDrop,
    children,
    ...restProps
  } = props;
  // console.log('--EditTableRow--record--index--:', record, index)
  // dataSource === [] 时 record + index === undefined
  if (record === undefined && index === undefined) return null;
  const [form] = YmForm.useForm(); //每调用一次就生成新的FormInstance

  const {
    attributes,
    listeners,
    setNodeRef,
    setActivatorNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({
    id: restProps['data-row-key'],
  });

  const style: React.CSSProperties = {
    transform: CSS.Transform.toString(transform && { ...transform, scaleY: 1 }),
    transition,
    ...(isDragging ? { position: 'relative', zIndex: 9999 } : {}),
  };

  //当前行的rowKey不变时，当前函数式组件不会卸载然后重新加载！
  useEffect(() => {
    addFormInstance(record[rowKey], form);
    let isAddBtnAdd = true; //不是初始化的recored而是添加按钮添加的
    for (let i = 0; i < fieldNames.length; i++) {
      if (
        record[fieldNames[i]] !== undefined &&
        record[fieldNames[i]] !== null
      ) {
        isAddBtnAdd = false;
      }
    }
    // console.log('--EditTableRow--record--:', record);
    let newRecord = record;
    if (isAddBtnAdd && formInitialValues) {
      newRecord = { ...record, ...formInitialValues };
    }
    form.setFieldsValue(newRecord);
    return () => {
      removeFormInstance(record[rowKey]);
    };
  }, []);

  return (
    <YmForm
      name={record[rowKey]}
      form={form}
      onValuesChange={(changedValues, allValues) => {
        // console.log('--changedValues--allValues--:', changedValues, allValues);
        onRowValuesChange?.(index, {
          ...record,
          ...allValues, //因为表单联动，这里采用allValues,因为只有Input.onChange--updateValue--才会触发onValuesChange
          [rowKey]: record[rowKey],
        });
      }}
      component={false} //为 false 则不创建 form 标签
      initialValues={formInitialValues}
    >
      <EditTableRowContext.Provider value={{ form }}>
        <tr {...restProps} ref={setNodeRef} style={style} {...attributes}>
          {React.Children.map(children, (child) => {
            //这时候child.props.children还未渲染
            if ((child as React.ReactElement).key === 'sort') {
              return React.cloneElement(child as React.ReactElement, {
                children: (
                  <MenuOutlined
                    ref={setActivatorNodeRef}
                    style={{ touchAction: 'none', cursor: 'move' }}
                    {...listeners}
                  />
                ),
              });
            }
            return child;
          })}
        </tr>
      </EditTableRowContext.Provider>
    </YmForm>
  );
};

export default EditTableRow;
